import { post } from './request'
import Taro from '@tarojs/taro'

// 声明微信JS-SDK的全局类型
declare global {
  interface Window {
    wx: any
  }
  const wx: any
}

/**
 * 微信分享配置接口
 */
interface WechatShareConfig {
  appId: string
  timestamp: string
  nonceStr: string
  signature: string
  url: string
  jsapiTicket: string
}

/**
 * 分享参数接口
 */
interface ShareParams {
  title: string
  desc: string
  link: string
  imgUrl: string
}

/**
 * 微信分享工具类
 */
export class WechatShare {
  private static instance: WechatShare
  private config: WechatShareConfig | null = null
  private isInitialized = false

  private constructor() {}

  static getInstance(): WechatShare {
    if (!WechatShare.instance) {
      WechatShare.instance = new WechatShare()
    }
    return WechatShare.instance
  }

  /**
   * 获取微信JSSDK配置
   */
  async getJSSDKConfig(url: string = 'https://www.h5.nl9555.com'): Promise<WechatShareConfig> {
    try {
      console.log('🔄 获取微信JSSDK配置...')
      
      const response = await post('https://www.api.nl9555.com/weChat/JSSDK', { url })
      
      console.log('📡 JSSDK接口响应:', response)
      
      if (response.code === 0) {
        this.config = response.data
        console.log('✅ JSSDK配置获取成功:', this.config)
        return this.config
      } else {
        throw new Error(response.message || '获取JSSDK配置失败')
      }
    } catch (error) {
      console.error('❌ 获取JSSDK配置失败:', error)
      throw error
    }
  }

  /**
   * 初始化微信JS-SDK
   */
  async initWechatSDK(url?: string): Promise<void> {
    try {
      const config = await this.getJSSDKConfig(url)
      
      if (!this.isWechatEnvironment()) {
        console.log('⚠️ 非微信环境，跳过SDK初始化')
        return
      }

      if (typeof wx !== 'undefined') {
        wx.config({
          debug: false,
          appId: config.appId,
          timestamp: config.timestamp,
          nonceStr: config.nonceStr,
          signature: config.signature,
          jsApiList: [
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'requestMerchantTransfer'
          ]
        })

        wx.ready(() => {
          console.log('✅ 微信JS-SDK初始化成功')
          this.isInitialized = true
        })

        wx.error((res: any) => {
          console.error('❌ 微信JS-SDK初始化失败:', res)
          this.isInitialized = false
        })
      }
    } catch (error) {
      console.error('❌ 初始化微信SDK失败:', error)
      throw error
    }
  }

  /**
   * 设置分享参数
   */
  setShareConfig(params: ShareParams): void {
    if (!this.isWechatEnvironment() || typeof wx === 'undefined') {
      return
    }

    // 新版分享接口
    if (wx.updateAppMessageShareData) {
      wx.updateAppMessageShareData({
        title: params.title,
        desc: params.desc,
        link: params.link,
        imgUrl: params.imgUrl,
        success: () => console.log('✅ 分享给朋友配置成功'),
        fail: (res: any) => console.error('❌ 分享给朋友配置失败:', res)
      })

      wx.updateTimelineShareData({
        title: params.title,
        link: params.link,
        imgUrl: params.imgUrl,
        success: () => console.log('✅ 分享到朋友圈配置成功'),
        fail: (res: any) => console.error('❌ 分享到朋友圈配置失败:', res)
      })
    }

    // 旧版分享接口
    if (wx.onMenuShareAppMessage) {
      wx.onMenuShareAppMessage({
        title: params.title,
        desc: params.desc,
        link: params.link,
        imgUrl: params.imgUrl,
        success: () => console.log('✅ 旧版分享配置成功')
      })

      wx.onMenuShareTimeline({
        title: params.title,
        link: params.link,
        imgUrl: params.imgUrl,
        success: () => console.log('✅ 旧版朋友圈分享配置成功')
      })
    }
  }

  /**
   * 检查是否在微信环境中
   */
  private isWechatEnvironment(): boolean {
    const systemInfo = Taro.getSystemInfoSync()
    return systemInfo.platform === 'wechat' || 
           systemInfo.platform === 'weapp' ||
           (typeof window !== 'undefined' && /MicroMessenger/i.test(navigator.userAgent))
  }

  /**
   * 检查SDK是否已初始化
   */
  isSDKReady(): boolean {
    return this.isInitialized && this.isWechatEnvironment()
  }
}

// 导出单例实例
export const wechatShare = WechatShare.getInstance()

/**
 * 默认分享配置
 */
export const defaultShareConfig: ShareParams = {
  title: '能力都市',
  desc: '让天下没有难找的收入',
  link: 'https://www.h5.nl9555.com',
  imgUrl: 'https://www.h5.nl9555.com/share.jpg'
} 